package general.conflictset;

public class ArrayConflictSet implements ConflictSet {

	boolean[] conflicts;
	byte max;
	int n;

	public ArrayConflictSet(int n){
		this.n = n;
		this.max = -1;
		conflicts = new boolean[n];
		reset();
	}

	public ArrayConflictSet(byte[] conflicts){
		this.n = conflicts.length;
		this.conflicts = new boolean[n];
		this.max=-1;
		for (byte j=0; j<n; j++){
			this.conflicts[j] = (conflicts[j]==1);
			if (isConflicting(j)) max = (byte)Math.max(max, j);
		}
	}

	@Override
	public void insert(byte i) {
		conflicts[i] = true;
		max = (byte)Math.max(max, i);
	}

	@Override
	public boolean isConflicting(byte i) {
		return conflicts[i];
	}

	@Override
	public void remove(byte i) {
		conflicts[i] = false;
		if (i==max){
			max = -1;
			for (byte j=0; j<n; j++){
				if (isConflicting(j)) max = (byte)Math.max(max, j);
			}
		}

	}

	@Override
	public void reset() {
		for (int i=0; i<n; i++){
			conflicts[i] = false;
		}
		max = -1;
	}

	@Override
	public byte max() {
		return max;
	}

	@Override
	public byte[] getBytes() {
		byte[] ans = new byte[n];
		ans[0] = 0x00;
		for (byte i=0; i<n; i++){
			ans[i] = (conflicts[i] ? (byte)1 : 0);
		}
		return ans;
	}

//	@Override
//	public void removeBigger(byte h) {
//		for (byte i=h; i<n; i++){
//			remove(i);
//		}
//	}

	@Override
	public void addAll(ConflictSet conflicts) {
		for (byte i=0; i<n; i++){
			if (conflicts.isConflicting(i)){
				insert(i);
			}
		}
	}

	@Override
	public String toString() {
//		if (max==-1) return "[]";
//		else {
			String ans = "[";
			for (int i=0; i<conflicts.length; i++){
				if (conflicts[i]) ans = ans + i + ", ";
			}
//			ans = ans + max + "]";
			if (ans.length()>2) ans = ans.substring(0, ans.length()-2);
			ans = ans + "]";
			return ans;
//		}

	}
}
